package edu.uwo.se2.group3mapapp;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.xmlpull.v1.XmlPullParserException;

import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;

public class FriendsActivity extends Activity {

	int userId = -1;
	List<Friend> users = new ArrayList<Friend>();
	List<Friend> friends = new ArrayList<Friend>();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_friends);

		Intent intent = getIntent();
		userId = intent.getIntExtra(LoginActivity.USER_ID, -1);

		
		// TODO we need to pass in the user Id
		new getFriendsList().execute(userId);

		Log.d("UID", "" + userId);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.friends, menu);
		return true;
	}

	public void addFriend(View v) {
		new addFriendTask().execute();
	}

	private class addFriendTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... arg0) {
			Spinner s = (Spinner) findViewById(R.id.friendSelector);
			int pos = s.getSelectedItemPosition();
			int fid = users.get(pos).friendId;

			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // must be created from activity and passed in
			if (Utilities.isNetworkAvailable(connectivityManager)) {
				HttpURLConnection connection = null;
				HttpResponse response = null;
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g3/addfriend.php?userId="+userId+"&friendId="+fid);
					response = httpclient.execute(httppost);
				} catch (MalformedURLException e) {
					System.out.println("Bad URL");
				} catch (IOException e) {
					System.out.println("Unable to retrieve web page");
				} finally {
					if (connection != null)
						connection.disconnect();
				}

				//			HttpEntity r_entity = response.getEntity();
				//			String xmlString = "";
				//			
				//			try {
				//				xmlString = EntityUtils.toString(r_entity);
				//			} catch (ParseException e) {
				//				// TODO Auto-generated catch block
				//				e.printStackTrace();
				//			} catch (IOException e) {
				//				// TODO Auto-generated catch block
				//				e.printStackTrace();
				//			}
				//			ByteArrayInputStream xml = new ByteArrayInputStream(xmlString.getBytes());
				//			
				//			UserParser up = new UserParser();
				//			
				//			Response<User> users = new Response<User>();
				//			try {
				//				users = up.parse(xml);
				//			} catch (XmlPullParserException e) {
				//				// TODO Auto-generated catch block
				//				e.printStackTrace();
				//			} catch (IOException e) {
				//				// TODO Auto-generated catch block
				//				e.printStackTrace();
				//			}
				//			
				//			return users;
			}
			new getFriendsList().execute(userId);
			return "";
		}
	}

	public void deleteFriend(View v){
		new deleteFriendTask().execute();
	}

	private class deleteFriendTask extends AsyncTask<Void, Void, String> {

		@Override
		protected String doInBackground(Void... arg0) {
			Spinner s = (Spinner) findViewById(R.id.friendSelector);
			int pos = s.getSelectedItemPosition();
			int fid = users.get(pos).friendId;

			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // must be created from activity and passed in
			if (Utilities.isNetworkAvailable(connectivityManager)) {
				HttpURLConnection connection = null;
				HttpResponse response = null;
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g3/deleteFriend.php?userId="+userId+"&friendId="+fid);
					response = httpclient.execute(httppost);
				} catch (MalformedURLException e) {
					System.out.println("Bad URL");
				} catch (IOException e) {
					System.out.println("Unable to retrieve web page");
				} finally {
					if (connection != null)
						connection.disconnect();
				}
			}
			new getFriendsList().execute(userId);
			return "";
		}
	}

	private class getFriendsList extends AsyncTask<Integer, Void, Response<Friend>> {

		@Override
		protected Response<Friend> doInBackground(Integer... args) {
			ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); // must be created from activity and passed in
			if (Utilities.isNetworkAvailable(connectivityManager)) {
				HttpURLConnection connection = null;
				HttpResponse response = null;
				try {
					HttpClient httpclient = new DefaultHttpClient();
					HttpPost httppost = new HttpPost("http://softeng.cs.uwosh.edu/students/cs342g3/getFriendRequestsAndUsers.php?userId=" + args[0]);
					response = httpclient.execute(httppost);
				} catch (MalformedURLException e) {
					System.out.println("Bad URL");
				} catch (IOException e) {
					System.out.println("Unable to retrieve web page");
				} finally {
					if (connection != null)
						connection.disconnect();
				}

				HttpEntity r_entity = response.getEntity();
				String xmlString = "";

				try {
					xmlString = EntityUtils.toString(r_entity);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ByteArrayInputStream xml = new ByteArrayInputStream(xmlString.getBytes());

				FriendParser fp = new FriendParser();

				Response<Friend> friends = new Response<Friend>();
				try {
					friends = fp.parse(xml);
				} catch (XmlPullParserException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				return friends;

			} else {
				Response<Friend> r = new Response<Friend>();
				r.status.isSuccessful = false;
				r.status.content = "Android device has no internet access";
				return r;
			}
		}

		@Override
		public void onPostExecute(Response<Friend> usersFrom) {
			ListView listNames = (ListView) findViewById(R.id.friendList);
			Spinner userNames = (Spinner) findViewById(R.id.friendSelector);
			friends = new ArrayList<Friend>();
			users = usersFrom.list;
			for (Friend f: usersFrom.list) {
				if (f.state == 1)
					friends.add(f);
			}
			
			ArrayList<String> a = new ArrayList<String>();
			for (Friend u: usersFrom.list) {
				if (u.friendId != userId) {
					a.add(u.friendUsername + u.state());
				}
				System.out.println(u.toString());
			}
			UserAdapter friendsAdapter = new UserAdapter(FriendsActivity.this, friends);
			ArrayAdapter<String> userAdapter = new ArrayAdapter<String>(FriendsActivity.this, android.R.layout.simple_spinner_item, a);
			
			userNames.setAdapter(userAdapter);
			listNames.setAdapter(friendsAdapter);

			//			listNames.setOnItemClickListener(new OnItemClickListener() {
			//				public void onItemClick(AdapterView<?> parent, View view,
			//						int position, long id) {
			//					int tempUser = userIds.get(users.indexOf(parent
			//							.getItemAtPosition(position)));
			//					// DatabaseHandler db = new
			//					// DatabaseHandler(getApplicationContext());
			//					// db.markAllMessagesAsRead(tempUser);
			//					Intent intent = new Intent(ListNamesActivity.this,
			//							MessagesActivity.class);
			//					intent.putStringArrayListExtra("users", users);
			//					intent.putIntegerArrayListExtra("ids", userIds);
			//					intent.putExtra(
			//							"toId",
			//							userIds.get(users.indexOf(parent.getItemAtPosition(
			//									position).toString())));
			//					startActivity(intent);
			//
			//					// finish();
			//				}
			//			});
			// listNamesAdapter.notifyDataSetChanged();
		}


	}

}
